<template>
  <PageContainer>
    <view class="container">
      <Header title="选择会员" :is-box-shadow="false">
        <template>
          <view class="px-15 py-8 bgf disFlxAC">
            <view style="flex: 1">
              <UniSearchBar
                v-model.trim="params.keyword"
                placeholder="姓名/手机号/单位"
                cancelButton="none"
                radius="35"
                bgColor="#F5F5F5"
                @confirm="refresh"
                @clear="resetFnc"
              ></UniSearchBar>
            </view>
            <view class="pl-15 fz-40" @click="toTypeSelection">
              <view
                class="ali-icon icon-shaixuan1 fz-24"
                :style="{ color: typeSelected.length ? '#2878ff' : '#CCCCC8' }"
              ></view>
            </view>
          </view>
          <view class="linh-40 px-15 fz-14 disFlxJS" style="background-color: #f5f5f5">
            <view>
              <text>已选 {{ checkedList.length + '/' + totalNumber }} 人</text>
            </view>
          </view>
        </template>
      </Header>
      <view class="mt-8">
        <Paglist
          v-model="dataList"
          :is-init-api="false"
          :parame="params"
          @register="register"
          :scroll-top-bottom="200"
          :is-show-loadmore="dataList.length > 1"
        >
          <template v-for="item in dataList" :key="item.userId">
            <UserItem
              :userInfo="item"
              :is-checked="hasChecked(item.id)"
              :type="type"
              @change-checked="changeChecked"
            />
          </template>
        </Paglist>
      </view>
      <TButtonGroup position="fixed" :styles="{ backgroundColor: '#FFF' }">
        <TButton
          class="gutter-btn"
          :text="`确认添加(${checkedList.length})`"
          type="primary"
          @click="confirm"
        />
      </TButtonGroup>
    </view>
  </PageContainer>
</template>

<script lang="ts" setup>
  /* publicSelectUserList 选择用户 */
  import Header from '@/components/Header/index.vue';
  import PageContainer from '@/components/PageContainer/index.vue';
  import { provide, reactive, ref, unref } from 'vue';
  import Paglist from '@/components/Paglist/index.vue';
  import { useConList } from '@/components/Paglist/useConList';
  import { getMemberList, getMemberStatistics } from '@/api/admin';
  import type { MsgUserData, SearchUserData } from '@/api/admin/types';
  import { navigateBack, navigateTo, onLoad } from '@/router';
  import UserItem from './components/UserItem.vue';
  import TButtonGroup from '@/components/TButtonGroup/index.vue';
  import TButton from '@/components/TButtonGroup/TButton.vue';
  import { onPageScroll } from '@dcloudio/uni-app';
  import type { PublicSelectUserList, TypeSelectedItem } from '@/router/types/modules';
  import UniSearchBar from '@/uni_modules/uni-search-bar/components/uni-search-bar/uni-search-bar.vue';
  import type { ClassTypeListResult } from '@/api/indexTypes';
  import { getClassTypeList } from '@/api';
  import dictionary from '@/utils/dictionary';
  import { MemberRoleEnum } from '@/enums/memberRoleEnum';

  const selectedList = ref<PublicSelectUserList['selectedList']>([]);
  const checkedList = ref<PublicSelectUserList['selectedList']>([]);
  const type = ref<PublicSelectUserList['type']>('checkbox');
  let success: PublicSelectUserList['success'];

  provide('api', async (obj: SearchUserData) => {
    obj.size = params.size;
    const res = await getMemberList(obj);
    return res;
  });

  const totalNumber = ref(0);

  const params = reactive<SearchUserData>({
    current: 1,
    size: 10,
    dataSource: 'memberList',
    initRoleIds: [MemberRoleEnum.PRINCIPAL], // 单位身份
    keyword: '',
    levelIds: [], // 职务
    industryIds: [], // 行业
    applyType: [], // 用户类型
    groupIds: [], // 用户标签
    memberStateIds: [], // 会员状态
    paymentStatusIds: [], // 缴费状态
  });

  const [register, { refresh }] = useConList();
  const dataList = ref<MsgUserData[]>([]);

  const resetFnc = () => {
    params.keyword = '';
    refresh();
  };

  onLoad<'publicSelectUserList'>((op) => {
    type.value = op.type;
    params.dataSource = op.dataSource;
    params.initRoleIds = op.initRoleIds;
    selectedList.value = op.selectedList;
    checkedList.value = op.selectedList;
    success = op.success
    getMemberStatistics({ dataSource: op.dataSource }).then((res) => {
      totalNumber.value = res.personNumber;
    });

    refresh && refresh();
  });

  const hasChecked = (memberId: string) => {
    return checkedList.value.includes(memberId);
  };

  function changeChecked(memberId: string) {
    if (type.value === 'checkbox') {
      if (hasChecked(memberId)) {
        checkedList.value = checkedList.value.filter((item) => item !== memberId);
      } else {
        checkedList.value.push(memberId);
      }
      return;
    }

    if (type.value === 'radio') {
      checkedList.value = hasChecked(memberId) ? [] : [memberId];
      return;
    }
  }

  // 跳转多条件筛选人员页面
  const typeSelected = ref<TypeSelectedItem[]>([]);
  function toTypeSelection() {
    navigateTo({
      name: 'typeSelection',
      options: {
        localData: unref(localData),
        selected: unref(typeSelected),
        success: (arr) => {
          typeSelected.value = arr;
          // 获取职务
          params.levelIds = arr.filter((v) => v.key === 'memberLevel').map((v) => v.id) as number[];
          // 获取行业
          params.industryIds = arr
            .filter((v) => v.key === 'industryId')
            .map((v) => v.id) as number[];
          // 获取用户标签
          params.groupIds = arr.filter((v) => v.key === 'memberGroup').map((v) => v.id) as number[];
          // 获取单位身份
          // params.initRoleIds = arr
          //   .filter((v) => v.key === 'unitLevel')
          //   .map((v) => v.id) as number[];
          refresh();
        },
      },
    });
  }

  /** 重组类型数据格式 */
  async function regroupClassTypeList() {
    const typeList = await getClassTypeList(['memberLevel', 'industryId', 'memberGroup']);
    return typeList.reduce((obj, v) => {
      obj[v.key] = v;
      return obj;
    }, {} as Recordable<ClassTypeListResult>);
  }

  const localData = ref<ClassTypeListResult[]>([]);
  async function _getLocalData() {
    const { memberLevel, industryId, memberGroup } = await regroupClassTypeList();
    localData.value.push(industryId); // 行业
    localData.value.push(memberLevel); // 职务
    localData.value.push(memberGroup); // 用户标签
    // localData.value.push(unitLevel()); // 单位身份
  }

  function unitLevel() {
    const _r = dictionary.getLocal('memberLevel');
    return {
      key: 'unitLevel',
      name: '单位身份',
      list: _r.map((v, i) => {
        return {
          id: Number(v.dictValue),
          name: v.dictValue !== '0' ? `会员-${v.dictLabel}` : v.dictLabel,
        };
      }),
    } as ClassTypeListResult;
  }

  _getLocalData();

  function confirm() {
    success?.(unref(checkedList));
    navigateBack();
  }

  onPageScroll(() => {});
</script>

<style lang="scss" scoped></style>
